<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入名称" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="指标类别" prop="category">
            <el-select v-model="queryParams.category" placeholder="请选择指标类别" clearable>
              <el-option v-for="dict in assess_system_index_category" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="描述" prop="description">
            <el-input v-model="queryParams.description" placeholder="请输入描述" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="父节点" prop="parentId">
            <el-input v-model="queryParams.parentId" placeholder="请输入父节点" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="逆向指标" prop="inversed">
            <el-select v-model="queryParams.inversed" placeholder="请选择是否为逆向指标" clearable>
              <el-option v-for="dict in assess_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="体系内码" prop="systemTypeId">
            <el-input v-model="queryParams.systemTypeId" placeholder="请输入体系内码" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()"
              v-hasPermi="['assess/system:systemData:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="systemDataList" row-key="id" :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" ref="systemDataTableRef">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="指标类别" align="center" prop="category">
          <template #default="scope">
            <dict-tag :options="assess_system_index_category" :value="scope.row.category" />
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="description" />
        <!-- <el-table-column label="父节点" align="center" prop="parentId" /> -->
        <el-table-column label="是否为逆向指标" align="center" prop="inversed">
          <template #default="scope">
            <dict-tag :options="assess_yes_no" :value="scope.row.inversed" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="体系内码" align="center" prop="systemTypeId" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['assess/system:systemData:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                v-hasPermi="['assess/system:systemData:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['assess/system:systemData:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改指标体系数据对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="systemDataFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父节点" prop="parentId">
          <el-tree-select v-model="form.parentId" :data="systemDataOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择父节点"
            check-strictly />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="指标类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择指标类别">
            <el-option v-for="dict in assess_system_index_category" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="逆向指标" prop="inversed">
          <el-radio-group v-model="form.inversed">
            <el-radio v-for="dict in assess_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="体系内码" prop="systemTypeId">
          <el-input v-model="form.systemTypeId" placeholder="请输入体系内码" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SystemData" lang="ts">
import { addSystemData, delSystemData, getSystemData, listSystemData, updateSystemData } from "@/api/assess/system/systemData";
import { SystemDataForm, SystemDataQuery, SystemDataVO } from '@/api/assess/system/systemData/types';

const props = defineProps({
  status: {
    type: Object,
    default() {
      return {}
    }
  }
})

watch(() => props.status.systemTypeData, () => {
  getList();
}, {
  deep: true
})


type SystemDataOption = {
  id: number;
  name: string;
  children?: SystemDataOption[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;;

const { assess_system_index_category, assess_yes_no } = toRefs<any>(proxy?.useDict('assess_system_index_category', 'assess_yes_no'));

const systemDataList = ref<SystemDataVO[]>([]);
const systemDataOptions = ref<SystemDataOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const systemDataFormRef = ref<ElFormInstance>();
const systemDataTableRef = ref<ElTableInstance>()

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});


const initFormData: SystemDataForm = {
  id: undefined,
  name: undefined,
  category: undefined,
  description: undefined,
  parentId: undefined,
  inversed: 'assess_yes_no_n',
  systemTypeId: undefined
}

const data = reactive<PageData<SystemDataForm, SystemDataQuery>>({
  form: { ...initFormData },
  queryParams: {
    name: undefined,
    category: undefined,
    description: undefined,
    parentId: undefined,
    inversed: undefined,
    systemTypeId: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    category: [
      { required: true, message: "指标类别不能为空", trigger: "change" }
    ],
    parentId: [
      { required: true, message: "父节点不能为空", trigger: "blur" }
    ],
    inversed: [
      { required: true, message: "是否为逆向指标不能为空", trigger: "change" }
    ],
    systemTypeId: [
      { required: true, message: "体系内码不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询指标体系数据列表 */
const getList = async () => {
  const systemTypeData = props.status.systemTypeData;
  if (!systemTypeData || systemTypeData.systemType == "assess_node_type_group") {
    queryParams.value.systemTypeId = undefined;
    form.value.systemTypeId = undefined;
    initFormData.systemTypeId = undefined;
  } else if (systemTypeData.systemType == "assess_node_type_data") {
    queryParams.value.systemTypeId = systemTypeData.id;
    form.value.systemTypeId = systemTypeData.id;
    initFormData.systemTypeId = systemTypeData.id;
  }
  loading.value = true;
  const res = await listSystemData(queryParams.value);
  const data = proxy?.handleTree<SystemDataVO>(res.data, "id", "parentId");
  if (data) {
    systemDataList.value = data;
    loading.value = false;
  }
}

/** 查询指标体系数据下拉树结构 */
const getTreeselect = async () => {
  const res = await listSystemData();
  systemDataOptions.value = [];
  const data: SystemDataOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<SystemDataOption>(res.data, "id", "parentId");
  systemDataOptions.value.push(data);
}

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
}

// 表单重置
const reset = () => {
  form.value = { ...initFormData }
  systemDataFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = (row?: SystemDataVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = "添加指标体系数据";
}

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(systemDataList.value, isExpandAll.value)
}

/** 展开/折叠操作 */
const toggleExpandAll = (data: SystemDataVO[], status: boolean) => {
  data.forEach((item) => {
    systemDataTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row: SystemDataVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getSystemData(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改指标体系数据";
}

/** 提交按钮 */
const submitForm = () => {
  systemDataFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSystemData(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addSystemData(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row: SystemDataVO) => {
  await proxy?.$modal.confirm('是否确认删除指标体系数据编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delSystemData(row.id).finally(() => loading.value = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

onMounted(() => {
  getList();
});
</script>
